package main

import (
	"context"
	"fmt"
	"io"
	"log"
	"net/http"
	"os"
	"os/signal"
	"time"
)

func main() {

	http.HandleFunc("/", HelloServer)
	err := http.ListenAndServe(":8080", nil)
	//equivalent to Print() followed by a call to os.Exit(1).
	log.Fatal(err)
}

func HelloServer(w http.ResponseWriter, req *http.Request) {
	req.ParseForm()                 //populates r.Form and r.PostForm.  类型map[string][]string
	fmt.Println("Form: ", req.Form) //url上参数+body form参数
	fmt.Println("URL: ", req.URL)   //相对于context的路径，包含后面参数

	fmt.Fprintf(w, "Hello") //写入到w

	//log.Println(req)
	//io.WriteString(w, "hello world!\n")
}

func draining() {
	// subscribe to SIGINT signals
	stopChan := make(chan os.Signal)
	signal.Notify(stopChan, os.Interrupt)

	mux := http.NewServeMux()
	mux.Handle("/",
		http.HandlerFunc(func(respW http.ResponseWriter, req *http.Request) {
			time.Sleep(5 * time.Second)
			io.WriteString(respW, "Finished!")
		}),
	)
	server := &http.Server{Addr: ":8081", Handler: mux}

	go func() {
		if err := server.ListenAndServe();
			err != nil {
			log.Printf("listen: %s\n", err)
		}
	}()

	<-stopChan // wait for SIGINT

	log.Println("Shutting down server...")
	//WithTimeout returns WithDeadline(parent, time.Now().Add(timeout)).
	ctx, _ := context.WithTimeout(context.Background(), 5*time.Second)
	// 等待request结束，非强制关闭。若context过期，则直接返回error，结束。
	server.Shutdown(ctx)
	// 也可以调用srv.Close()立即停止http.Server
}
